package br.mikhas.container.factory.processor;

import br.mikhas.container.config.BeanDefinition;
import br.mikhas.container.factory.BeanFactory;
import br.mikhas.container.factory.BeanFactoryAware;
import br.mikhas.container.factory.BeanPostProcessor;

/**
 * Provides the instance of the bean factory to the {@link BeanFactoryAware}
 * resources.
 * 
 * @author Mikhail Domanoski
 * 
 */
public class BeanFactoryProviderPostProcessor implements BeanPostProcessor {

	/**
	 * The bean factory instance which will be providen to the resources.
	 */
	private BeanFactory beanFactory;

	/**
	 * Accepts the resources which implements {@link BeanFactoryAware}
	 * interface.
	 */
	@Override
	public boolean mayProcess(BeanDefinition definition) {
		Class<?> resourceType = definition.getType();
		return BeanFactoryAware.class.isAssignableFrom(resourceType);
	}

	/**
	 * Sets the {@link BeanFactory} on the {@link BeanFactoryAware} resources.
	 */
	@Override
	public Object processBean(BeanDefinition definition, Object resource) {
		BeanFactoryAware bfa = (BeanFactoryAware) resource;
		bfa.setBeanFactory(this.beanFactory);
		return resource;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

}
